
package com.borqs.music.ui.online;

import static android.content.DialogInterface.BUTTON_POSITIVE;
import static com.borqs.music.util.MusicUtils.DownloadDefs.DOWNLOAD_INTENT_KEY_NEED_SHOW_TOAST;
import static com.borqs.music.util.MusicUtils.DownloadDefs.DOWNLOAD_INTENT_KEY_SINGLE_ITEM;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;

import com.borqs.music.DownloadService;
import com.borqs.music.MediaPlaybackService;
import com.borqs.music.R;
import com.borqs.music.model.DownloadItem;
import com.borqs.music.model.SongInfo;
import com.borqs.music.util.AccountUtils;
import com.borqs.music.util.MusicUtils;
import com.borqs.music.util.MusicUtils.ServiceToken;
import com.borqs.music.util.MyLogger;

public class OnlineBaseActivity extends ListActivity implements ServiceConnection, MusicUtils.Defs {
    private static final String NEED_PROMPT_NO_WIFI_KEY = "need_prompt_when_no_available_wifi";
    private static final MyLogger logger = MyLogger.getLogger("OnlineBaseActivity");
    private ServiceToken mToken;
    protected String mTicket;
    private Toast mToast = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        setContentView(R.layout.entry_list);

        getListView().setOnCreateContextMenuListener(this);

        Activity realActivity = getParent();
        if (realActivity == null) {
            realActivity = this;
        }
        mToken = MusicUtils.bindToService(realActivity, this);
        MusicUtils.addNowPlayingListener(this);

        mTrackIntentFilter = new IntentFilter();
        mTrackIntentFilter.addAction(MediaPlaybackService.META_CHANGED);
        mTrackIntentFilter.addAction(MediaPlaybackService.QUEUE_CHANGED);
        mTrackIntentFilter.addAction(MediaPlaybackService.PLAYSTATE_CHANGED);
        mTicket = AccountUtils.getUserData(this,
                AccountUtils.BORQS_ACCOUNT_OPTIONS_KEY_SESSION);

        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    }

    @Override
    protected void onResume() {
        super.onResume();

        registerReceiver(mTrackListListener, mTrackIntentFilter);
        mTrackListListener.onReceive(null, null);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mTrackListListener);
    }

    @Override
    protected void onDestroy() {
        if (mToken != null) {
            MusicUtils.unbindFromService(mToken);
        }
        super.onDestroy();
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicUtils.updateNowPlaying(this);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        finish();
    }

    private IntentFilter mTrackIntentFilter;
    private BroadcastReceiver mTrackListListener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            MusicUtils.updateNowPlaying(OnlineBaseActivity.this);
            getListView().invalidateViews();
        }
    };

    protected void downloadSingleSong(final SongInfo song, final boolean needToast) {
        if (!song.isNotInDevice) {
            Toast.makeText(OnlineBaseActivity.this,
                    R.string.songs_exist_in_local, Toast.LENGTH_SHORT).show();
            return;
        }
        if(!checkActiveNetworkStatus()){
            return;
        }

        if (checkWifiNetworkStatus()) {
            downloadSong(song, needToast);
        }else{
            DialogInterface.OnClickListener dealWhenNotWifiListener = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    saveCheckIntoPrefer((AlertDialog) dialog);
                    if (whichButton == BUTTON_POSITIVE) {
                        downloadSong(song, needToast);
                    }
                }
            };
            LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.prompt_network_dialog, null);
            new AlertDialog.Builder(getRealActivity(this))
                    .setTitle(R.string.dialog_no_active_wifi_title)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setView(textEntryView)
                    .setPositiveButton(android.R.string.ok, dealWhenNotWifiListener)
                    .setNegativeButton(android.R.string.cancel, dealWhenNotWifiListener)
                    .create().show();
        }
    }

    private void downloadSong(SongInfo song, boolean needToast) {
        DownloadItem item = new DownloadItem(song.id, song.title, song.artist,
                getFileName(song), song.fileMd5, song.isFavorite);
        Intent intent = new Intent(this, DownloadService.class);
        intent.setAction(DownloadService.ACTION_START_DOWNLOAD);
        intent.putExtra(DOWNLOAD_INTENT_KEY_SINGLE_ITEM, item);
        intent.putExtra(DOWNLOAD_INTENT_KEY_NEED_SHOW_TOAST, needToast);
        startService(intent);
    }

    protected void playsong(final List<SongInfo> songs, final int position) {
        if(!checkActiveNetworkStatus()){
            return;
        }

        if (checkWifiNetworkStatus()) {
            playOnlineSongs(songs, position);
        } else {
            DialogInterface.OnClickListener dealWhenNotWifiListener = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    saveCheckIntoPrefer((AlertDialog) dialog);
                    if (whichButton == BUTTON_POSITIVE) {
                        playOnlineSongs(songs, position);
                    }
                }
            };
            LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.prompt_network_dialog, null);
            new AlertDialog.Builder(getRealActivity(this))
                    .setTitle(R.string.dialog_no_active_wifi_title)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setView(textEntryView)
                    .setPositiveButton(android.R.string.ok, dealWhenNotWifiListener)
                    .setNegativeButton(android.R.string.cancel, dealWhenNotWifiListener)
                    .create().show();
        }
    }

    private void playOnlineSongs(List<SongInfo> songs, int position) {
        try {
            MusicUtils.sService.openOnlineSong(songs, position);
            MusicUtils.sService.play();
        } catch (RemoteException e) {
            logger.e(e.getMessage());
        }
    }

    private void saveCheckIntoPrefer(AlertDialog dialog) {
        CheckBox checkBox = (CheckBox) ((AlertDialog) dialog)
                .findViewById(R.id.checkbox_no_more_prompt);
        if (checkBox.isChecked()) {
            SharedPreferences pre = PreferenceManager
                    .getDefaultSharedPreferences(OnlineBaseActivity.this);
            Editor editor = pre.edit();
            editor.putBoolean(NEED_PROMPT_NO_WIFI_KEY, false);
            editor.commit();
        }
    }

    public static String getFileName(SongInfo song) {
        if (song.isPublicSong) {
            return song.artist + "-" + song.title + "." + song.fileType;
        }
        return song.fileName;
    }

    public void showToast(String msg, int duration) {
        mToast.setText(msg);
        mToast.setDuration(duration);
        mToast.show();
    }

    public void showToast(int id) {
        showToast(getString(id), Toast.LENGTH_LONG);
    }

    public void showToast(String msg) {
        showToast(msg, Toast.LENGTH_LONG);
    }

    public void showToast(int id, int duration) {
        showToast(getString(id), duration);
    }

    public Activity getRealActivity(Activity activity) {
        Activity realActivity = activity;
        Activity parentActivity = realActivity.getParent();
        while (parentActivity != null) {
            realActivity = parentActivity;
            parentActivity = realActivity.getParent();
        }
        return realActivity;
    }

    protected boolean checkActiveNetworkStatus() {
        if (MusicUtils.isNetworkEnabled(this)) {
            return true;
        } else {
            MusicUtils.getCheckNetworkDialog(getRealActivity(this)).show();
            return false;
        }
    }

    protected boolean checkWifiNetworkStatus() {
        ConnectivityManager cm = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeInfo = cm.getActiveNetworkInfo();

        if (null != activeInfo && !activeInfo.getTypeName().equalsIgnoreCase("WIFI")) {

            SharedPreferences pre = PreferenceManager.getDefaultSharedPreferences(this);

            boolean needPrompt = pre.getBoolean(NEED_PROMPT_NO_WIFI_KEY, true);
            if (needPrompt) {
                return false;
            }
        }
        return true;
    }
}
